<?php

$product_code = $path[3];

if ($product_code) {
	$product = $db->fetchRow("SELECT * FROM shop_products WHERE code=? AND site_id=?", array($product_code, $site['id']));
	
	if ($product['deleted']) {
		echo "This product has been deleted.";
		exit;
	}
	
	if (!$product) {
		$product = array('code' => $product_code, 'site_id' => $site['id'], 'path' => make_path($product_code));
		$db->insert('shop_products', $product);
	}
}

if ($product) {
	
	$errors = array();
	
	if ($_POST) {
		
		// update the product.
		foreach($_POST['product'] as $key => $value) {
			if ($value == '') $_POST['product'][$key] = new Zend_Db_Expr('NULL');
		}
		$db->update('shop_products', array_merge($product, $_POST['product']), $db->quoteInto("id=?", $product['id']));
		
		// update the categories
		$db->delete('shop_categories_products', $db->quoteInto('product_id=?', $product['id']));
		foreach($_POST['categories'] as $category_id) {
			$db->insert('shop_categories_products', array(
				'category_id' => $category_id,
				'product_id'  => $product['id'],
				'master'      => 1
			));
			
			$parent_category_sql = "SELECT parent_id FROM shop_categories WHERE id=?";
			$parent_category_id = $db->fetchOne($parent_category_sql, $category_id);
			while($parent_category_id) {
				try {
					$db->insert('shop_categories_products', array(
						'category_id' => $parent_category_id,
						'product_id'  => $product['id'],
						'master'      => 0
					));
					$parent_category_id = $db->fetchOne($parent_category_sql, $parent_category_id);
				} catch (Exception $e) {
					// if this fails, it's because a parent category is already a master.
					// so break out of the loop.
					break;
				}
			}
		}
		
		$db->delete('shop_products_prices', $db->quoteInto("product_id=?", $product['id']));
		foreach($_POST['price'] as $price) {
			if (is_numeric($price['price'])) {
				$db->insert('shop_products_prices', array(
					'product_id'       => $product['id'],
					'minimum_quantity' => $price['minimum_quantity'],
					'price'            => $price['price']
				));
			}
		}
		
		foreach($_POST['simpleattributes'] as $simpleattribute) {
			if (!$simpleattribute['title']) continue;
			// does this already exist?
			$simpleattribute_id = $db->fetchOne("SELECT id FROM shop_products_simpleattributes WHERE title=?", $simpleattribute['title']);
			if (!$simpleattribute_id) {
				echo "INSERTING\n";
				$db->insert('shop_products_simpleattributes', array(
					'title' => $simpleattribute['title'],
					'type'  => $simpleattribute['type']
				));
				$simpleattribute_id = $db->lastInsertId();
			}
			
			$max_sort = $db->fetchOne("SELECT MAX(sort) FROM shop_products_simpleattributes_products WHERE product_id=?", $product['id']);
			
			try {
				$db->insert('shop_products_simpleattributes_products', array(
					'product_id'         => $product['id'],
					'simpleattribute_id' => $simpleattribute_id,
					'sort'               => $simpleattribute['sort'] ? $simpleattribute['sort'] : ($max_sort + 10),
					'image_prefix'       => $simpleattribute['image_prefix']
				));
			} catch (Zend_Db_Statement_Exception $e) {
				if (strpos($e->getMessage(), "Integrity constraint violation") !== false) {
					// already exists, so update
					$db->update('shop_products_simpleattributes_products', array(
						'sort'               => $simpleattribute['sort'] ? $simpleattribute['sort'] : ($max_sort + 10),
						'image_prefix'       => $simpleattribute['image_prefix']
					), $db->quoteInto('product_id=?', $product['id']) . ' AND ' . $db->quoteInto('simpleattribute_id=?', $simpleattribute_id));
				} else {
					throw $e;
				}
			}
			
			$db->delete('shop_products_simpleattributes_values', $db->quoteInto('product_id=?', $product['id']) . ' AND ' . $db->quoteInto('simpleattribute_id=?', $simpleattribute_id));
			if ($simpleattribute['type'] == 'select' and isset($simpleattribute['values'])) {
				foreach($simpleattribute['values'] as $value) {
					if (!$value['value']) continue;
					$db->insert('shop_products_simpleattributes_values', array(
						'product_id' => $product['id'],
						'simpleattribute_id' => $simpleattribute_id,
						'value' => $value['value'],
						'price' => $value['price'],
						'sort' => $value['sort']
					));
				}
			}
			
		}
		
		$db->delete('shop_products_metas_values', $db->quoteInto('product_id=?', $product['id']));
		foreach($_POST['meta'] as $meta) {
			if (!$meta['title']) continue;
			$title_id = $db->fetchOne("SELECT id FROM shop_products_metas WHERE title=?", $meta['title']);
			if (!$title_id) {
				$db->insert('shop_products_metas', array('title' => $meta['title']));
				$title_id = $db->lastInsertId();
			}
			
			$db->insert('shop_products_metas_values', array(
				'product_id' => $product['id'],
				'meta_id'    => $title_id,
				'value'      => $meta['value'],
				'sort'       => $meta['sort']
			));
			
		}
		
		if ($_POST['new_attribute']) {
			
			$attribute_id = $db->fetchOne("SELECT id FROM shop_products_attributes WHERE title=?", $_POST['new_attribute']);
			if (!$attribute_id) $db->insert('shop_products_attributes', array(
				'title' => $_POST['new_attribute']
			));
			$attribute_id = $db->lastInsertId();
			
			$max_sort = $db->fetchOne("SELECT MAX(sort) FROM shop_products_attributes_products WHERE product_id=?", $product['id']);
			try {
				$db->insert('shop_products_attributes_products', array(
					'product_id'   => $product['id'],
					'attribute_id' => $attribute_id,
					'sort'         => $max_sort + 10
				));
			} catch (Zend_Db_Statement_Exception $e) {
				if (strpos($e->getMessage(), "Integrity constraint violation") !== false) {
					// do nothing
				} else {
					throw $e;
				}
			}
			
		}
		
		foreach($_POST['attribute_sort'] as $attribute_id => $sort) {
			$db->update('shop_products_attributes_products', 
				array('sort' => $sort), 
				$db->quoteInto('product_id=?', $product['id']) . ' AND ' . $db->quoteInto('attribute_id=?', $attribute_id)
			);
		}
		
		

		
		
		
		if ($_POST['new_sub_product']) {
			
			$exists = $db->fetchOne("SELECT id FROM shop_products WHERE code=? AND site_id=?", array($_POST['new_sub_product'], $site['id']));
			
			if ($exists) {
				$errors[] = "There is already a product with the reqested sub-product code.";
			} else {
				$db->insert('shop_products', array(
					'site_id' => $site['id'],
					'parent_id' => $product['id'],
					'code' => $_POST['new_sub_product'],
					'path' => new Zend_Db_Expr('NULL')
				));
			}
		}
		
		
		$db->delete('shop_products_attributes_values', $db->quoteInto('product_id=?', $product['id']));
		foreach($_POST['attribute'] as $attribute_id => $value) {
			$db->insert('shop_products_attributes_values', array(
				'product_id'   => $product['id'],
				'attribute_id' => $attribute_id,
				'value'        => $value
			));
		}
		
		// update the product we've got in memory
		$product = $db->fetchRow("SELECT * FROM shop_products WHERE code=? AND site_id=?", array($product_code, $site['id']));
		
	}
	
	
	if ($product['parent_id']) {
		$product['parent'] = $db->fetchRow("SELECT * FROM shop_products WHERE id=?", $product['parent_id']);
		$product['attributes'] = $db->fetchAll("SELECT attribute_id, title, value FROM shop_products_attributes_values pav JOIN shop_products_attributes pa ON pav.attribute_id=pa.id WHERE pav.product_id=?", $product['id']);
		$product['attributes'] = array_index($product['attributes'], 'attribute_id');
	}
	
	$smarty->assign('product', $product);
	
	$smarty->assign('prices', $db->fetchAll("SELECT * FROM shop_products_prices WHERE product_id=? ORDER BY minimum_quantity", $product['id']));
	$smarty->assign('ranges', $db->fetchAll("SELECT * FROM shop_ranges ORDER BY title"));
	
	$simpleattributes = $db->fetchAll("SELECT id, title, type, image_prefix, sort FROM shop_products_simpleattributes_products sp JOIN shop_products_simpleattributes s ON sp.simpleattribute_id=s.id WHERE product_id=? ORDER BY sort", $product['id']);
	foreach($simpleattributes as &$simpleattribute) {
		$simpleattribute['values'] = $db->fetchAll("SELECT value, price, sort FROM shop_products_simpleattributes_values WHERE product_id=? AND simpleattribute_id=? ORDER BY sort", array($product['id'], $simpleattribute['id']));
	}
	$smarty->assign('simpleattributes', $simpleattributes);
	
	$smarty->assign('all_categories', $db->fetchCol("SELECT category_id FROM shop_categories_products WHERE product_id=? AND master=1", $product['id']));

	$categories = require $app_root . '/admin/frontend/_modules/shop/navigation.php';
	$smarty->assign('categories', $categories);
	
	$attributes = $db->fetchAll("SELECT pap.*, pa.title FROM shop_products_attributes_products pap JOIN shop_products_attributes pa ON pap.attribute_id=pa.id WHERE product_id=? ORDER BY sort", ($product['parent'] ? $product['parent']['id'] : $product['id']));
	$subproducts = $db->fetchAll("SELECT * FROM shop_products WHERE parent_id=? AND deleted=0", $product['id']);
	foreach($subproducts as &$subproduct) {
		$subproduct['attributes'] = array();
		foreach($attributes as $attribute) {
			$subproduct['attributes'][$attribute['attribute_id']] = $db->fetchRow("SELECT * FROM shop_products_attributes_values WHERE product_id=? AND attribute_id=? ORDER BY sort", array($subproduct['id'], $attribute['attribute_id']));
		}
	}
	$smarty->assign('attributes', $attributes);
	$smarty->assign('subproducts', $subproducts);
	
	$metas = $db->fetchAll("SELECT title, value, sort FROM shop_products_metas_values pmv JOIN shop_products_metas pm ON pmv.meta_id=pm.id WHERE product_id=? ORDER BY sort", $product['id']);
	$smarty->assign('metas', $metas);
	
	$smarty->assign('errors', $errors);
	
	if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) and $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest') {
		header('Content-type: text/xml');
		$smarty->display('shop/products/edit.tpl.taconite');
	} else {
		$smarty->display('shop/products/edit.tpl.html');
	}
}

else {
	header('Location: /admin/shop/products/');
}
